import 'dart:async';

import 'package:flutter/material.dart';

import '../../../base/base_model.dart';
import '../../../resources.dart';

/// created by hcl
/// on 2025/2/4
/// ChangePhoneModel
/// desc
class ChangePhoneModel extends BaseModel {
  TextEditingController phoneController = TextEditingController();
  FocusNode phoneFocusNode = FocusNode();
  TextEditingController codeController = TextEditingController();
  FocusNode codeFocusNode = FocusNode();

  var currentTime = -1;
  Timer? currentTimer;

  @override
  void initData() {}

  @override
  void dispose() {
    super.dispose();
    stopTimer();
  }

  getCode() {
    if (currentTime < 0) {
      if (phoneController.text.isEmpty) {
        showToast(word.please_phone_new);
        return;
      }
      Toast.showLoading();
      Future.delayed(const Duration(seconds: 2), () {
        Toast.close();
        startTimer();
      });
    }
  }

  checkCode() {
    if (phoneController.text.isEmpty) {
      showToast(word.please_phone_new);
      return;
    }
    if (codeController.text.isEmpty) {
      showToast(word.please_enter_code);
      return;
    }
    Toast.showLoading();
    Future.delayed(const Duration(seconds: 2), () {
      Toast.close();
    });
  }

  void startTimer() {
    currentTime = 60;
    Timer.periodic(const Duration(seconds: 1), (timer) {
      if (currentTimer != timer) {
        if (currentTimer != null) {
          currentTimer!.cancel();
          currentTimer = null;
        }
        currentTimer = timer;
      }
      currentTime--;
      if (currentTime < 0) {
        currentTimer!.cancel();
        currentTimer = null;
      }
    });
  }

  void stopTimer() {
    if (currentTimer != null) {
      currentTimer!.cancel();
      currentTimer = null;
      currentTime = -1;
    }
  }
}
